/*
 * @Author: your name
 * @Date: 2021-05-17 10:45:22
 * @LastEditTime: 2021-05-18 10:42:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vite-project/src/router/guard/permissionGuard.ts
 */
import type { Router, RouteRecordRaw } from 'vue-router';

import { usePermissionStoreWidthOut } from '@/store/modules/permission';
import { useUserStoreWidthOut } from '@/store/modules/user';

const whitePathList = ["/login"];


export function createPermissionGuard(router: Router) { 

    const userStore = useUserStoreWidthOut();
    const permissionStore = usePermissionStoreWidthOut();
    router.beforeEach( async (to, from, next) => {
        
        if(whitePathList.includes(to.path)) {
            next();
            return;
        }

        const token = userStore.getToken;

        //没有token
        if (!token) {
            //meta中设置不需要权限的，可以进入
            if (to.meta.ignoreAuth) {
                next();
                return;
            }
            //重定向到登录页面
            const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
                path: "/login",
                replace: true
            };
            if (to.path) {
                redirectData.query = {
                    ...redirectData.query,
                    redirect: to.path
                };
            }
            next(redirectData);
            return;
        }

        if (permissionStore.getIsDynamicAddedRoute) {
            next();
            return;
        }
        const routes = await permissionStore.buildRoutesAction();

        routes.forEach( route => {
            router.addRoute((route as unknown) as RouteRecordRaw);
        });

        const redirectPath = (from.query.redirect || to.path) as string;
        const redirect = decodeURIComponent(redirectPath);
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
        permissionStore.setDynamicAddedRoute(true);
        next(nextData);
    })
}
